package com.markus.code.剑指offer;

import java.util.ArrayList;
import java.util.List;

/**
 * Author:markusZhang
 * Date:Create in 2020/9/11 17:18
 * todo: 二叉树和为某一值的路径
 */
public class PathSum {
    public static class TreeNode{
        int val;
        TreeNode left;
        TreeNode right;
        public TreeNode(int val){
            this.val = val;
        }
    }
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> ans = new ArrayList<>();
        if (root == null){
            return ans;
        }
        process(root,sum,0,new ArrayList<>(),ans);
        return ans;
    }
    private void process(TreeNode root,int sum,int curSum,List<Integer> path,List<List<Integer>> ans){
        if (root == null){
            return ;
        }
        curSum += root.val;
        path.add(root.val);
        if (curSum == sum){
            if (root.left == null && root.right == null){
                ans.add(new ArrayList<>(path));
            }
        }
        process(root.left, sum, curSum, path, ans);
        process(root.right, sum, curSum, path, ans);
        path.remove(path.size()-1);
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(5);
        root.left = new TreeNode(4);
        root.right = new TreeNode(8);
        root.left.left = new TreeNode(11);
        root.left.left.left = new TreeNode(7);
        root.left.left.right = new TreeNode(2);
        root.right = new TreeNode(8);
        root.right.left = new TreeNode(13);
        root.right.right = new TreeNode(4);
        root.right.right.left = new TreeNode(5);
        root.right.right.right = new TreeNode(1);
        PathSum demo = new PathSum();
        List<List<Integer>> lists = demo.pathSum(root, 22);
        System.out.println(lists);
    }
}
